#include "linkstack.h"


node_t *CreateLinkStack(void)
{
    node_t *top = malloc(sizeof(node_t));
    if (top == NULL)
    {
        printf("创建空间失败\n");
        return NULL;
    }
    memset(top, 0, sizeof(node_t));

    top->next = NULL;

    return top;
}


int isEmptyLinkStack(node_t *top)
{
    return (top == NULL) ? 0 : -1;
}

// 入栈
int PushLinkStack(node_t *top, data_t mydata)
{
    node_t *p = malloc(sizeof(node_t));
    if (p == NULL)
    {
        printf("创建空间失败\n");
        return -1;
    }
    memset(p, 0, sizeof(node_t));

    p->data = mydata;

    p->next = top->next;
    top->next = p;

    return 0;
}

// 出栈
data_t PopLinkStack(node_t *top)
{
    if (isEmptyLinkStack(top) == 0)
    {
        printf("栈空\n");
        return -1;
    }

    node_t *p = top->next;
    top->next = p->next;

    data_t mydata = p->data;
    free(p);

    return mydata;
}

int LenthLinkList(node_t *top)
{
    int len = 0;

    node_t *p = top;

    while (p->next != NULL)
    {
        len++;
        p = p->next;
    }

    return len;
}

int DisplayLinkStack(node_t *top)
{
    if (isEmptyLinkStack(top) == 0)
    {
        printf("栈空\n");
        return -1;
    }

    node_t *p = top->next;
    while (p != NULL)
    {
        printf("%-4d", p->data);
        p = p->next;
    }
    printf("\n");

    return 0;
}
